"use client";
import { useChat } from "../hook/usechat";
import { send } from "../action/chat";
import InputForm from "./input";
import Memo from "./memo";
import Banner from "./banner";
import Context from "./context";
import { useEffect, useState } from "react";
import { getRouters } from "../action/router";

export default function Page() {
  const [router, SetRouter] = useState(null); // 当前路由名称
  const [list, SetList] = useState([]); // 聊天记录
  const [routers, SetRouters] = useState([]); // 路由列表
  const [loaded, SetLoaded] = useState(false); // 是否已经加载过路由列表

  // get router lists
  const router_list = async () => {
    // get router list
    const router_list = await getRouters();

    SetRouters(router_list);
    SetLoaded(true);
    SetRouter(router_list[0].name);
  };

  useEffect(() => {
    router_list();
  }, []);

  const { messages, input, handleInputChange, handleSubmit } = useChat({
    action: send,
  });

  return (
    <div>
      {loaded ? (
        <Context.Provider value={{ router, SetRouter, list, SetList, routers }}>
          <div className="h-screen w-full overflow-y-auto">
            <div className="flex-no-wrap flex h-full flex-col overflow-y-auto">
              <div className="sticky top-0 z-10 min-h-0 min-w-0 flex-shrink-0">
                <Banner />
              </div>

              <div className="min-w-0 flex-1">
                <div className="scrolling-touch scrolling-gpu relative h-full w-full overflow-auto overscroll-y-auto pb-12">
                  <div className="divide-y">
                    <Memo />
                  </div>
                </div>
              </div>

              <div>
                {messages.map((m) => (
                  <div key={m.id} className="whitespace-pre-wrap">
                    {m.role === "user" ? "User: " : "AI: "}
                    {m.content}
                  </div>
                ))}
              </div>

              <div className="sticky bottom-0 min-h-0 min-w-0 flex-shrink-0">
                <div className="bg-white/70 p-3 pr-2.5 shadow-[0_-1px_rgba(229,231,235,.53),0_5px_20px_-5px_rgba(0,0,0,.24)] backdrop-blur">
                  <InputForm handleSubmit={handleSubmit} />
                </div>
              </div>
            </div>
          </div>
        </Context.Provider>
      ) : (
        <div>Loading...</div>
      )}
    </div>
  );
}
